from fastapi import APIRouter, Query
from fastapi.responses import JSONResponse
from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_ollama import ChatOllama
from ..settings.settings import Settings
from openai import OpenAI

router = APIRouter()

# -----------------------------
# 定义 ChatPromptTemplate
# -----------------------------
prompt = ChatPromptTemplate.from_template(
    "请以 JSON 格式输出{name}的诗歌信息，包括title、author、content"
)

# -----------------------------
# 本地 Ollama 模型
# -----------------------------
llm = ChatOllama(
    model="qwen3:0.6b",
    base_url="http://172.16.21.38:11436"
)

# 初始化 JSON 解析器
parser = JsonOutputParser()


@router.get("/poem_info")
async def poem_info(name: str = Query(..., description="诗的名称")):
    """调用本地 Ollama 模型，返回指定诗歌的 JSON 信息"""
    # 渲染消息
    prompt_messages = prompt.format_messages(name=name)
    # 调用 LLM
    response = llm.invoke(prompt_messages)
    # 解析 JSON
    try:
        data = parser.parse(response.content)
    except Exception as e:
        return JSONResponse(
            content={
                "error": "模型返回内容无法解析为 JSON",
                "details": str(e),
                "raw_output": response.content
            },
            status_code=500
        )
    return JSONResponse(content={"poem_info": data})


# -----------------------------
# 云端 DeepSeek 模型
# -----------------------------
# 读取配置
settings = Settings()
DeepSeekUrl = settings.DeepSeekUrl
DeepSeekKey = settings.DeepSeekKey

# 初始化 OpenAI 客户端
client = OpenAI(api_key=DeepSeekKey, base_url=DeepSeekUrl)


@router.get("/poem_info_deepseek")
async def poem_info_deepseek(name: str = Query(..., description="诗的名称")):
    """调用云端 DeepSeek 模型，返回指定诗歌的 JSON 信息"""
    # 渲染消息
    prompt_messages = prompt.format_messages(name=name)
    # 提取 human 的内容
    user_content = " ".join([m.content for m in prompt_messages if m.type == "human"])
    # 调用 DeepSeek API
    response = client.chat.completions.create(
        model="deepseek-chat",  # 云端 DeepSeek 模型
        messages=[{"role": "user", "content": user_content}],
        temperature=0.7
    )
    # 获取输出
    text_output = response.choices[0].message.content
    # 解析 JSON
    try:
        data = parser.parse(text_output)
    except Exception as e:
        return JSONResponse(
            content={
                "error": "模型返回内容无法解析为 JSON",
                "details": str(e),
                "raw_output": text_output
            },
            status_code=500
        )
    return JSONResponse(content={"poem_info_deepseek": data})
